/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.swak.mmap;

import java.nio.ByteBuffer;
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.swak.nativex.nativeio.NativeIO;

/**
 * 使用文件存储时在前面加一个 内存的缓冲区；
 * 
 * @author 618lf
 */
@Deprecated
public class TransientStorePool {
	private static final Logger log = LoggerFactory.getLogger(TransientStorePool.class);

	private final int poolSize;
	private final int fileSize;
	private final Deque<ByteBuffer> availableBuffers;

	public TransientStorePool(int poolSize, int fileSize) {
		this.poolSize = poolSize;
		this.fileSize = fileSize;
		this.availableBuffers = new ConcurrentLinkedDeque<>();
	}

	/**
	 * It's a heavy init method.
	 */
	public void init() {
		for (int i = 0; i < poolSize; i++) {
			ByteBuffer byteBuffer = ByteBuffer.allocateDirect(fileSize);
			try {
				NativeIO.mlock(byteBuffer, fileSize);
			} catch (Exception e) {
			}
			availableBuffers.offer(byteBuffer);
		}
	}

	public void destroy() {
		for (ByteBuffer byteBuffer : availableBuffers) {
			try {
				NativeIO.munlock(byteBuffer, fileSize);
			} catch (Exception e) {
			}
		}
	}

	public void returnBuffer(ByteBuffer byteBuffer) {
		byteBuffer.position(0);
		byteBuffer.limit(fileSize);
		this.availableBuffers.offerFirst(byteBuffer);
	}

	public ByteBuffer borrowBuffer() {
		ByteBuffer buffer = availableBuffers.pollFirst();
		if (availableBuffers.size() < poolSize * 0.4) {
			log.warn("TransientStorePool only remain {} sheets.", availableBuffers.size());
		}
		return buffer;
	}

	public int availableBufferNums() {
		return availableBuffers.size();
	}
}
